package nju.mscs.server.businessLogic;
import java.util.*;

import nju.mscs.data.object.*;
import nju.mscs.data.object.Date;


public class SM implements StorageManager{
	public final static int ADD=0;
	public final static int DELETE=1;
	public final static int CHANGE=2;
	public static ArrayList<String[]> add=new ArrayList<String[]>();
	public static ArrayList<String> delete=new ArrayList<String>();
	public static ArrayList<String[]> change=new ArrayList<String[]>();
	private String userId;
	private Database db;
	private ArrayList<String> reasonList;
	public SM(){
		db=Controller.sumDB;
	}
	
	@Override
	public String[][] storageAnalysis() {
		// TODO Auto-generated method stub
		Iterator<Goods> gl=db.getInventory();
		int n=0;
		while(gl.hasNext()){
			Goods good=gl.next();
			Date d=good.getOutTime();
			Calendar ca=Calendar.getInstance();
			Calendar time=Calendar.getInstance();
			time.set(d.getYear(), d.getMonth(), d.getDate());			
			long l1=ca.getTimeInMillis();    
			long l2=time.getTimeInMillis();    
			long storeDays = (l2-l1)/(24*60*60*1000); 
			d=good.getInTime();
			time.set(d.getYear(), d.getMonth(), d.getDate());
			l2=time.getTimeInMillis();
			long ruleDays=(l1-l2)/(24*60*60*1000);
			int circulate=good.getBeforeAmount()+good.getLastAmount()-good.getAmount();
			String predictTime=null;
			String predictScrap=null;
			if(circulate>0){
				int predict=Math.min(circulate/(int)ruleDays,(int)storeDays);
				if(predict<=storeDays)
					predictScrap="0";
				else
					predictScrap=(predict-(int)storeDays)/predict+"";
				predictTime=predict+"";
			}
			good.setPredictTime(predictTime);
			good.setPredictScrap(predictScrap);
			n++;
		}
		gl=db.getInventory();
		String[][] result=new String[n][5];
		int i=0;
		while(gl.hasNext()){
			Goods good=gl.next();
			result[i][0]=good.getId();
			result[i][1]=good.getName();
			result[i][2]=good.getPrice()+"";
			result[i][3]=good.getPredictTime();
			result[i][4]=good.getPredictScrap();
			i++;
		}
		return result;
	}


	@Override
	public boolean createChange(String[][] inf) {
		// TODO Auto-generated method stub
		for(String[] infor:inf){
			add.add(infor);
			db.addGoods(infor[2], Integer.parseInt(infor[1]), infor[2], 0);
		}
		return true;
	}


	@Override
	public boolean deleteChange(String[] inf) {
		// TODO Auto-generated method stub
		for(String infor:inf){
			delete.add(infor);
			db.deleteGoods(infor);
		}
		return true;
	}


	@Override
	public boolean changeChange(String[][] inf) {
		// TODO Auto-generated method stub
		for(String[] infor:inf){
			change.add(infor);
			Goods good=db.searchGoodsById(infor[0]);
			good.setName(infor[1]);
			good.setPrice(Integer.parseInt(infor[2]));
		}
		return true;
	}
}
